import * as bm from "/js/baseModule.js";
let EXIF = require('/js/exif.js');

export class Module extends bm.baseModule {
    constructor(view) {
        super(view);
        /**模块 */
        this.ImageUploader_vue = '';
        /**预览图片 */
        this.imgUrl ='';
        this.preview = '';
        /**上次input控件 */
        this.inputUpload = '';
        this.btnUpload = '';
        /**demand */
        this.demand = '';
        this.file = '';
        this.orientation = '';
        this.tempImg = '';

    }
    afterInstall() {
        this.imgUrl = this.find(".imageUrl");
        let that = this;
        let canvas = document.createElement('canvas');
        this.tempImg = document.createElement("img");
        this.tempImg.style.display = "none";
        $('body').append(this.tempImg);

        this.tempImg.onload = function (event) {
            let degree = 0, drawWidth, drawHeight, width, height;
            drawWidth = this.naturalWidth;
            drawHeight = this.naturalHeight;
            //改变图片大小
            if (drawWidth > 500) {//按最大高度等比缩放
                let rate = 500 / drawWidth;
                drawHeight = drawHeight * rate;
                drawWidth = 500;
            }
            canvas.width = width = drawWidth;
            canvas.height = height = drawHeight;
            let context = canvas.getContext('2d');
            if (context) {
                // 由于ios上传图片时，旋转拍摄的图片会倒置，方向不对，因此需要调整；
                //判断图片方向，重置canvas大小，确定旋转角度，iphone默认的是home键在右方的横屏拍摄方式
                switch (that.orientation) {
                    //iphone横屏拍摄，此时home键在左侧
                    case 3:
                        degree = 180;
                        drawWidth = -width;
                        drawHeight = -height;
                        break;
                    //iphone竖屏拍摄，此时home键在下方(正常拿手机的方向)
                    case 6:
                        canvas.width = height;
                        canvas.height = width;
                        degree = 90;
                        drawWidth = width;
                        drawHeight = -height;
                        break;
                    //iphone竖屏拍摄，此时home键在上方
                    case 8:
                        canvas.width = height;
                        canvas.height = width;
                        degree = 270;
                        drawWidth = -width;
                        drawHeight = height;
                        break;
                }
                //使用canvas旋转校正
                context.rotate(degree * Math.PI / 180);
                context.drawImage(this, 0, 0, drawWidth, drawHeight);
                that.demand.user_finish_img_info.img = canvas.toDataURL("image/jpeg");
                that.setImg();
            }
        };
        this.demand = globalData.current_demand;
        this.preview = this.find(".preview");
        this.btnUpload = this.find(".btn-upload ");
        this.inputUpload = this.find(".input-upload");
        /**删除预览 */
        this.preview.on('click', function () {
            that.demand.user_finish_img_info.img = '';
            that.tempImg.src = '';
            that.setImg();
            that.inputUpload.val('');
            //没有预览照片，按钮不可点击
            that.find(".btn").attr("disabled", "false");

        });
        /**预览上传图片 */
        this.inputUpload.on('change', function (event) {
            // 根据这个 <input> 获取文件的 HTML5 js 对象
            let files = event.target.files, file;
            if (files && files.length > 0) {
                // 获取目前上传的文件
                file = that.file = files[0];
                // 来在控制台看看到底这个对象是什么
                console.log(file);
                // 那么我们可以做一下诸如文件大小校验的动作
                // if (file.size > 1024 * 1024 * 2) {
                //     alert('图片大小不能超过 2MB!');
                //     return false;
                // }

                // 图片预览 function 1
                if (window['FileReader']) {
                } else {
                    alert("您的设备不支持图片预览功能，如需该功能请升级您的设备！");
                }
                let reader = new FileReader();
                let imageType = /^image\//;

                //是否是图片
                if (!imageType.test(file.type)) {
                    alert("请选择图片！");
                    return;
                }
                //处理IOS 拍照方向
                EXIF.getData(file, function () {
                    that.orientation = EXIF.getTag(this, 'Orientation');
                });
                reader.readAsDataURL(file);

                reader.onload = function () {
                    if (!this.result) return false;
                    that.tempImg.src = this.result;
                };
            }
            //按钮可点击
            that.find(".btn").removeAttr("disabled");

        });

        this.find(".btn").attr("disabled", "false");

        this.setImg();
    }
    setImg() {
        console.log('setImg succ');
        /**是否有图片 */
        if (this.demand.user_finish_img_info.img == "" || this.demand.user_finish_img_info.img == null) {
            this.imgUrl.attr('src', "");
            this.preview.addClass("hide");
            this.btnUpload.removeClass("hide");
        } else {
            this.imgUrl.attr('src', this.demand.user_finish_img_info.img);
            this.btnUpload.addClass("hide");
            this.preview.removeClass("hide");
            //按钮可点击
            this.find(".btn").removeAttr("disabled");
        }
    }
    /**上传文件，参数:文件地址 */
    fileUpload() {
        let that = this;
        let demand_id = this.demand.id;
        let formData = new FormData();
        let img = that.demand.user_finish_img_info.img;
        let imgBase64 = img.substr(img.indexOf(',') + 1);
        formData.append('img', imgBase64);
        $.ajax({
            url: APIURL+'/demand/'+demand_id+'/finish_img',
            type: 'POST',
            cache: false,
            data: JSON.stringify({"img":imgBase64}),
            dataType: "json",
            timeout: 30000,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'token': globalData.token
            },
            processData: false,
            contentType: false
        }).done(function (json) {
            console.log("::" + json.image);
            if (json.status == 200) {
                globalData.current_demand.user_finish_img_info.img = json.img;
                globalData.current_demand.user_finish_img_info.state = 0;
                that._evt_goback();
            } else {
                funs.tip('图片上传失败', '', 'fail');
            }
        }).fail(function (json) {
            funs.tip('服务器错误', '', 'fail')
        });
    }
    _evt_submit() {
        if (this.demand.user_finish_img_info.img == '' || this.demand.user_finish_img_info.img == null) {
            funs.tip('请先选择图片再提交', '', 'fail');
        } else if (this.demand.user_finish_img_info.state != -1) {
            funs.tip('本表单只能提交一次', '', 'fail');
        } else {
            this.fileUpload();
        }
    }
}
